﻿using UnityEngine;

namespace USClientKernel.Template
{
    public abstract class UGlobalSingleton<T> : MonoBehaviour where T : MonoBehaviour
    {
        protected static T _Instance;
        protected static GameObject _GlobalGameObject;
        protected static Transform _GlobalTransform;

        public static T Instance
        {
            get
            {
                if (null == _Instance)
                {
                    _Instance = GlobalGameObject.AddComponent<T>();
                }
                return _Instance;
            }
        }

        private void Awake()
        {
            Init();
        }

        virtual protected void Init()
        {

        }

        public static GameObject GlobalGameObject
        {
            get
            {
                _GlobalGameObject = GameObject.Find("UGlobalGameObject");
                if (null == _GlobalGameObject)
                {
                    _GlobalGameObject = new GameObject("UGlobalGameObject");
                    _GlobalTransform = _GlobalGameObject.transform;
                    DontDestroyOnLoad(_GlobalGameObject);
                }
                return _GlobalGameObject;
            }
        }

        public static Transform GlobalTransform
        {
            get
            {
                if (null == _GlobalTransform)
                {
                    _GlobalTransform = GlobalGameObject.transform;
                }
                return _GlobalTransform;
            }
        }

        private void OnApplicationQuit()
        {
            _Instance = null;
        }

    }
}
